package cn.brilliantfuture.commentry.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

/**
 * 
 * Title: Cabinet Platform
 * 
 * Author: LiTian
 * 
 * Date: 2012-9-13
 * 
 * Description: 获取JDBC数据源
 * 
 */
public class JDBCDataSource {
	
	private static Logger logger = Logger.getLogger(JDBCDataSource.class);
	private static DataSource dataSource = null;

	public static Connection getConnection() {

		try {
			if (null == dataSource) {
				Context ctx = new InitialContext();
				dataSource = (DataSource) ctx.lookup("java:/cabinetDatasource");
			}
			return dataSource.getConnection();
		} catch (NamingException e) {
			logger.error("Create jdbc datasource fail!\n" + e.getMessage());
			return null;
		} catch (SQLException e) {
			logger.error("Create jdbc datasource fail!\n" + e.getMessage());
			return null;
		}
	}
	
	public static void closeResource(Connection conn, PreparedStatement pstm, ResultSet rs){
		try {
			if (rs != null)
				rs.close();
			if (pstm != null)
				pstm.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
